package boardgamer.yavalath.client.preference;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import boardgamer.common.client.preference.PreferenceUpdater;
import boardgamer.yavalath.R;
import boardgamer.yavalath.client.SharedObjects;

import static boardgamer.common.client.preference.StringConverter.STRING_CONVERTER;
import static boardgamer.yavalath.client.Settings.KEY_COLOR_PLAYER_PREFIX;
import static boardgamer.yavalath.client.Settings.KEY_MUTED;
import static boardgamer.yavalath.client.Settings.KEY_NAME_PLAYER_PREFIX;

/**
 * @author garysoed
 */
public class YavalathPreference extends PreferenceActivity {
  
  private PreferenceUpdater preferenceUpdater;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
    PreferenceUpdater.Builder updaterBuilder
        = new PreferenceUpdater.Builder(sharedPreferences, this)
            .registerEditText(KEY_NAME_PLAYER_PREFIX + "-0", "Ysabel", STRING_CONVERTER)
            .register(
                KEY_COLOR_PLAYER_PREFIX + "-0",
                new RegisteredPlayerColorPicker(
                    0,  // PlayerId
                    (PlayerColorPickerPreference) findPreference(KEY_COLOR_PLAYER_PREFIX + "-0"),
                    sharedPreferences))
            .registerEditText(KEY_NAME_PLAYER_PREFIX + "-1", "Albert", STRING_CONVERTER)
            .register(
                KEY_COLOR_PLAYER_PREFIX + "-1",
                new RegisteredPlayerColorPicker(
                    1,  // PlayerId
                    (PlayerColorPickerPreference) findPreference(KEY_COLOR_PLAYER_PREFIX + "-1"),
                    sharedPreferences))
            .registerEditText(KEY_NAME_PLAYER_PREFIX + "-2", "Vorbis", STRING_CONVERTER)
            .register(
                KEY_COLOR_PLAYER_PREFIX + "-2",
                new RegisteredPlayerColorPicker(
                    2,  // PlayerId
                    (PlayerColorPickerPreference) findPreference(KEY_COLOR_PLAYER_PREFIX + "-2"),
                    sharedPreferences))
            .registerCheckBox(KEY_MUTED, false);
    SharedObjects.instance().getProFeatures().initializePreference(updaterBuilder);
    this.preferenceUpdater = updaterBuilder.build();
  }

  @Override
  protected void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences()
        .registerOnSharedPreferenceChangeListener(preferenceUpdater);
  }

  @Override
  protected void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences()
        .unregisterOnSharedPreferenceChangeListener(preferenceUpdater);
  }
}
